/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.dess.base.tools.delayed;

import lombok.Getter;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @project-name:dess
 * @package-name:com.hyts.dess.base.tools.delayed
 * @author:LiBo/Alex
 * @create-date:2020-08-11 16:31
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description:
 */
@Getter
public class DelayedEvent<T> implements Delayed {

    /**
     * id 主键关键字
     */
    private int id;

    /**
     * 消息体内容
     */
    private T body;

    /**
     * 执行时间
     * 延迟时长，这个是必须的属性因为要按照这个判断延时时长。
     */
    private long executeTime;

    /**
     * 构造器操作处理
     * @param id
     * @param body
     * @param delayTime
     */
    public DelayedEvent(int id, T body, long delayTime) {
        this.id = id;
        this.body = body;
        this.executeTime = TimeUnit.NANOSECONDS.convert(delayTime, TimeUnit.MILLISECONDS) + System.nanoTime();
    }

    /**
     *  获取延迟时间操作控制器
     * @param timeUnit
     * @return
     */
    @Override
    public long getDelay(TimeUnit timeUnit) {
        return timeUnit.convert(this.executeTime - System.nanoTime(), TimeUnit.NANOSECONDS);
    }

    /**
     * 自定义实现比较方法返回 1 0 -1 三个参数
     * @param delayed
     * @return
     */
    @Override
    public int compareTo(Delayed delayed) {
        DelayedEvent delayedEvent = (DelayedEvent)delayed;
        return this.id - delayedEvent.id;
    }
}
